jQuery(window).load(function() {

   // Page Preloader
   jQuery('#status').fadeOut();
   jQuery('#preloader').delay(350).fadeOut(function(){
      jQuery('body').delay(350).css({'overflow':'visible'});
  });
});

jQuery(document).ready(function() {

  window.onload = date_time('date_time');

   // Toggle Left Menu
   jQuery('.leftpanel .nav-parent > a').live('click', function() {

      var parent = jQuery(this).parent();
      var sub = parent.find('> ul');
      
      // Dropdown works only when leftpanel is not collapsed
      if(!jQuery('body').hasClass('leftpanel-collapsed')) {
       if(sub.is(':visible')) {
        sub.slideUp(200, function(){
         parent.removeClass('nav-active');
         jQuery('.mainpanel').css({height: ''});
         adjustmainpanelheight();
     });
    } else {
        closeVisibleSubMenu();
        parent.addClass('nav-active');
        sub.slideDown(200, function(){
         adjustmainpanelheight();
     });
    }
}
return false;
});
   
   function closeVisibleSubMenu() {
      jQuery('.leftpanel .nav-parent').each(function() {
       var t = jQuery(this);
       if(t.hasClass('nav-active')) {
        t.find('> ul').slideUp(200, function(){
         t.removeClass('nav-active');
     });
    }
});
  }

  function adjustmainpanelheight() {
      // Adjust mainpanel height
      var docHeight = jQuery(document).height();
      if(docHeight > jQuery('.mainpanel').height())
       jQuery('.mainpanel').height(docHeight);
}
adjustmainpanelheight();


   // Tooltip
   jQuery('.tooltips').tooltip({ container: 'body'});
   
   // Popover
   jQuery('.popovers').popover();
   
   // Close Button in Panels
   jQuery('.panel .panel-close').click(function(){
      jQuery(this).closest('.panel').fadeOut(200);
      return false;
  });
   
   // Form Toggles
   jQuery('.toggle').toggles({on: true});
   
   jQuery('.toggle-chat1').toggles({on: false});
   
   // Sparkline
   jQuery('#sidebar-chart').sparkline([4,3,3,1,4,3,2,2,3,10,9,6], {
      type: 'bar', 
      height:'30px',
      barColor: '#428BCA'
  });
   
   jQuery('#sidebar-chart2').sparkline([1,3,4,5,4,10,8,5,7,6,9,3], {
      type: 'bar', 
      height:'30px',
      barColor: '#D9534F'
  });
   
   jQuery('#sidebar-chart3').sparkline([5,9,3,8,4,10,8,5,7,6,9,3], {
      type: 'bar', 
      height:'30px',
      barColor: '#1CAF9A'
  });
   
   jQuery('#sidebar-chart4').sparkline([4,3,3,1,4,3,2,2,3,10,9,6], {
      type: 'bar', 
      height:'30px',
      barColor: '#428BCA'
  });
   
   jQuery('#sidebar-chart5').sparkline([1,3,4,5,4,10,8,5,7,6,9,3], {
      type: 'bar', 
      height:'30px',
      barColor: '#F0AD4E'
  });
   
   
   // Minimize Button in Panels
   jQuery('.minimize').click(function(){
      var t = jQuery(this);
      var p = t.closest('.panel');
      if(!jQuery(this).hasClass('maximize')) {
       p.find('.panel-body, .panel-footer').slideUp(200);
       t.addClass('maximize');
       t.html('&plus;');
   } else {
       p.find('.panel-body, .panel-footer').slideDown(200);
       t.removeClass('maximize');
       t.html('&minus;');
   }
   return false;
});
   
   
   // Add class everytime a mouse pointer hover over it
   jQuery('.nav-bracket > li').hover(function(){
      jQuery(this).addClass('nav-hover');
  }, function(){
      jQuery(this).removeClass('nav-hover');
  });
   
   
   // Menu Toggle
   jQuery('.menutoggle').click(function(){

      var body = jQuery('body');
      var bodypos = body.css('position');
      
      if(bodypos != 'relative') {

       if(!body.hasClass('leftpanel-collapsed')) {
        body.addClass('leftpanel-collapsed');
        jQuery('.nav-bracket ul').attr('style','');

        jQuery(this).addClass('menu-collapsed');

    } else {
        body.removeClass('leftpanel-collapsed chat-view');
        jQuery('.nav-bracket li.active ul').css({display: 'block'});

        jQuery(this).removeClass('menu-collapsed');

    }
} else {

   if(body.hasClass('leftpanel-show'))
    body.removeClass('leftpanel-show');
else
    body.addClass('leftpanel-show');

adjustmainpanelheight();         
}

});
   
   // Chat View
   jQuery('#chatview').click(function(){

      var body = jQuery('body');
      var bodypos = body.css('position');
      
      if(bodypos != 'relative') {

       if(!body.hasClass('chat-view')) {
        body.addClass('leftpanel-collapsed chat-view');
        jQuery('.nav-bracket ul').attr('style','');

    } else {

        body.removeClass('chat-view');

        if(!jQuery('.menutoggle').hasClass('menu-collapsed')) {
         jQuery('body').removeClass('leftpanel-collapsed');
         jQuery('.nav-bracket li.active ul').css({display: 'block'});
     } else {

     }
 }

} else {

   if(!body.hasClass('chat-relative-view')) {

    body.addClass('chat-relative-view');
    body.css({left: ''});

} else {
    body.removeClass('chat-relative-view');   
}
}

});
   
   reposition_topnav();

   jQuery(window).resize(function(){

      if(jQuery('body').css('position') == 'relative') {

       jQuery('body').removeClass('leftpanel-collapsed chat-view');

   } else {

       jQuery('body').removeClass('chat-relative-view');         
       jQuery('body').css({left: '', marginRight: ''});
   }

   if(jQuery('.leftpanel .searchform').length == 0)
    reposition_topnav();

});

   /* This function allows top navigation menu to move to left navigation menu
    * when viewed in screens lower than 1024px and will move it back when viewed
    * higher than 1024px
    */
    function reposition_topnav() {
      if(jQuery('.nav-horizontal').length > 0) {

         // top navigation move to left nav
         // .nav-horizontal will set position to relative when viewed in screen below 1024
         if(jQuery('.nav-horizontal').css('position') == 'relative') {

            if(jQuery('.leftpanel .nav-bracket').length == 2) {
             jQuery('.nav-horizontal').insertAfter('.nav-bracket:eq(1)');
         } else {
               // only add to bottom if .nav-horizontal is not yet in the left panel
               if(jQuery('.leftpanel .nav-horizontal').length == 0)
                  jQuery('.nav-horizontal').appendTo('.leftpanelinner');
          }

          jQuery('.nav-horizontal').css({display: 'block'})
          .addClass('nav-pills nav-stacked nav-bracket');

          jQuery('.nav-horizontal .children').removeClass('dropdown-menu');
          jQuery('.nav-horizontal > li').each(function() { 

             jQuery(this).removeClass('open');
             jQuery(this).find('a').removeAttr('class');
             jQuery(this).find('a').removeAttr('data-toggle');

         });

          if(jQuery('.nav-horizontal li:last-child').has('form')) {
             jQuery('.nav-horizontal li:last-child form').addClass('searchform').appendTo('.topnav');
             jQuery('.nav-horizontal li:last-child').hide();
         }
         
     } else {
            // move nav only when .nav-horizontal is currently from leftpanel
            // that is viewed from screen size above 1024
            if(jQuery('.leftpanel .nav-horizontal').length > 0) {

             jQuery('.nav-horizontal').removeClass('nav-pills nav-stacked nav-bracket')
             .appendTo('.topnav');
             jQuery('.nav-horizontal .children').addClass('dropdown-menu').removeAttr('style');
             jQuery('.nav-horizontal li:last-child').show();
             jQuery('.searchform').removeClass('searchform').appendTo('.nav-horizontal li:last-child .dropdown-menu');
             jQuery('.nav-horizontal > li > a').each(function() {

              jQuery(this).parent().removeClass('nav-active');

              if(jQuery(this).parent().find('.dropdown-menu').length > 0) {
               jQuery(this).attr('class','dropdown-toggle');
               jQuery(this).attr('data-toggle','dropdown');  
           }

       });              
         }

     }

 }
}

   // Sticky Header
   if(jQuery.cookie('sticky-header'))
      jQuery('body').addClass('stickyheader');

   // Sticky Left Panel
   if(jQuery.cookie('sticky-leftpanel')) {
      jQuery('body').addClass('stickyheader');
      jQuery('.leftpanel').addClass('sticky-leftpanel');
  }

   // Left Panel Collapsed
   if(jQuery.cookie('leftpanel-collapsed')) {
      jQuery('body').addClass('leftpanel-collapsed');
      jQuery('.menutoggle').addClass('menu-collapsed');
  }

   // Changing Skin
   var c = jQuery.cookie('change-skin');
   if(c) {
      jQuery('head').append('<link id="skinswitch" rel="stylesheet" href="css/style.'+c+'.css" />');
  }

   // Changing Font
   var fnt = jQuery.cookie('change-font');
   if(fnt) {
      jQuery('head').append('<link id="fontswitch" rel="stylesheet" href="css/font.'+fnt+'.css" />');
  }

   // Check if leftpanel is collapsed
   if(jQuery('body').hasClass('leftpanel-collapsed'))
      jQuery('.nav-bracket .children').css({display: ''});


   // Handles form inside of dropdown 
   jQuery('.dropdown-menu').find('form').click(function (e) {
      e.stopPropagation();
  });

  jQuery("#form").validate({
    highlight: function(element) {
      jQuery(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    success: function(element) {
      jQuery(element).closest('.form-group').removeClass('has-error');
    },
    submitHandler: function(form){
      form.submit();
    }
  });

  $('table.dataTableSimple').DataTable({
    "sPaginationType": "full_numbers"
  });

  tinymce.init({
      force_p_newlines : false,
      selector: "textarea.infoEditor",
      plugins: [
          "advlist autolink lists charmap print preview anchor",
          "searchreplace wordcount visualblocks code fullscreen",
          "insertdatetime contextmenu paste"
      ],
      toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"
  });
  tinymce.init({
      force_p_newlines : false,
      selector: "textarea.contentEditor",
      theme: "modern",
      plugins: [
          "advlist autolink lists link image charmap print preview hr anchor pagebreak",
          "searchreplace visualblocks visualchars code fullscreen",
          "insertdatetime media nonbreaking save table contextmenu directionality",
          "emoticons template paste textcolor jbimages"
      ],
      toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image jbimages",
      toolbar2: "print preview media | forecolor backcolor emoticons",
      image_advtab: true,
      relative_urls: false,
      templates: [
          {title: 'Test template 1', content: 'Test 1'},
          {title: 'Test template 2', content: 'Test 2'}
      ]
  });

});

function render_created_datatable(data,type,row,meta){
  var timestamp = moment.unix(row.created_at);
  return timestamp.format($date_format_jquery);
}  

function render_check_datatable(data,type,row,meta){
  var check = row.check;
  if(row.check == 1){
    check = '<a href="javascript:void(0)" class="btn btn-default tip active" art_id="'+row.id+'"><i class="fa fa-check"></a>';
  }else{
    check = '<a href="javascript:void(0)" class="btn btn-default tip active" art_id="'+row.id+'"><i class="fa fa-times"></a>';
  }
  return check;
}

function confirm_delete($id,$controller){
    bootbox.confirm("Are you sure?", function(result) {
        if(result == true){
            window.location.href = $admincp_url+$controller+'/delete/'+$id;
        }
    });
}

$.fn.dataTable.pipeline = function ( opts ) {
    // Configuration options
    var conf = $.extend( {
        pages: 5,     // number of pages to cache
        url: '',      // script url
        data: null,   // function or object with parameters to send to the server
                      // matching how `ajax.data` works in DataTables
        method: 'POST' // Ajax HTTP method
    }, opts );
 
    // Private variables for storing the cache
    var cacheLower = -1;
    var cacheUpper = null;
    var cacheLastRequest = null;
    var cacheLastJson = null;
 
    return function ( request, drawCallback, settings ) {
        var ajax          = false;
        var requestStart  = request.start;
        var drawStart     = request.start;
        var requestLength = request.length;
        var requestEnd    = requestStart + requestLength;
         
        if ( settings.clearCache ) {
            // API requested that the cache be cleared
            ajax = true;
            settings.clearCache = false;
        }
        else if ( cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper ) {
            // outside cached data - need to make a request
            ajax = true;
        }
        else if ( JSON.stringify( request.order )   !== JSON.stringify( cacheLastRequest.order ) ||
                  JSON.stringify( request.columns ) !== JSON.stringify( cacheLastRequest.columns ) ||
                  JSON.stringify( request.search )  !== JSON.stringify( cacheLastRequest.search )
        ) {
            // properties changed (ordering, columns, searching)
            ajax = true;
        }
         
        // Store the request for checking next time around
        cacheLastRequest = $.extend( true, {}, request );
 
        if ( ajax ) {
            // Need data from the server
            if ( requestStart < cacheLower ) {
                requestStart = requestStart - (requestLength*(conf.pages-1));
 
                if ( requestStart < 0 ) {
                    requestStart = 0;
                }
            }
             
            cacheLower = requestStart;
            cacheUpper = requestStart + (requestLength * conf.pages);
 
            request.start = requestStart;
            request.length = requestLength*conf.pages;
 
            // Provide the same `data` options as DataTables.
            if ( $.isFunction ( conf.data ) ) {
                // As a function it is executed with the data object as an arg
                // for manipulation. If an object is returned, it is used as the
                // data object to submit
                var d = conf.data( request );
                if ( d ) {
                    $.extend( request, d );
                }
            }
            else if ( $.isPlainObject( conf.data ) ) {
                // As an object, the data given extends the default
                $.extend( request, conf.data );
            }
 
            settings.jqXHR = $.ajax( {
                "type":     conf.method,
                "url":      conf.url,
                "data":     request,
                "dataType": "json",
                "cache":    false,
                "success":  function ( json ) {
                    cacheLastJson = $.extend(true, {}, json);
 
                    if ( cacheLower != drawStart ) {
                        json.data.splice( 0, drawStart-cacheLower );
                    }
                    json.data.splice( requestLength, json.data.length );
                     
                    drawCallback( json );
                }
            } );
        }
        else {
            json = $.extend( true, {}, cacheLastJson );
            json.draw = request.draw; // Update the echo for each response
            json.data.splice( 0, requestStart-cacheLower );
            json.data.splice( requestLength, json.data.length );
 
            drawCallback(json);
        }
    }
};
 
// Register an API method that will empty the pipelined data, forcing an Ajax
// fetch on the next draw (i.e. `table.clearPipeline().draw()`)
$.fn.dataTable.Api.register( 'clearPipeline()', function () {
    return this.iterator( 'table', function ( settings ) {
        settings.clearCache = true;
    } );
} );

// function showLoading($title, $html){
// 	new Messi(
// 		$html, 
// 		{
// 			title: $title, 
// 			modal: true,
// 			buttons: [{id: 2, label: 'Close', val: 'C'}]
// 		}
//        );
// }

function date_time(id){
  date = new Date;
  year = date.getFullYear();
  month = date.getMonth();
  months = new Array(
    '1', 
    '2', 
    '3', 
    '4', 
    '5', 
    '6', 
    '7', 
    '8', 
    '9', 
    '10', 
    '11', 
    '12'
  );
  d = date.getDate();
  day = date.getDay();
  days = new Array(
    'Chủ nhật', 
    'Thứ 2', 
    'Thứ 3', 
    'Thứ 4', 
    'Thứ 5', 
    'Thứ 6', 
    'Thứ 7'
  );
  h = date.getHours();
  if(h<10){
    h = "0"+h;
  }
  m = date.getMinutes();
  if(m<10){
    m = "0"+m;
  }
  s = date.getSeconds();
  if(s<10){
    s = "0"+s;
  }
  result = days[day]+', ngày '+d+' tháng '+months[month]+' năm '+year+' - '+h+':'+m+':'+s;
  document.getElementById(id).innerHTML = result;
  setTimeout('date_time("'+id+'");','1000');
  return true;
}